package com.tqz.rc.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Objects;

/**
 * <p>
 *
 * @author tianqingzhao
 * @since 2021/9/24 10:58
 */
public class InetUtils {

    private static final Logger log = LoggerFactory.getLogger(InetUtils.class);

    static final String NACOS_SERVER_IP = "nacos.server.ip";

    static final String IP_ADDRESS = "nacos.inetutils.ip-address";

    private static String selfIP;

    static {
        Runnable ipAutoRefresh = new Runnable() {
            @Override
            public void run() {
                String nacosIP = System.getProperty(NACOS_SERVER_IP);
                if (StringUtils.isBlank(nacosIP)) {
                    nacosIP = EnvUtil.getProperty(IP_ADDRESS);
                }
                String tmpSelfIP = nacosIP;
                if (StringUtils.isBlank(tmpSelfIP)) {

                    InetAddress inetAddress;
                    try {
                        inetAddress = InetAddress.getLocalHost();
                        if (inetAddress.getHostName().equals(inetAddress.getCanonicalHostName())) {
                            tmpSelfIP = inetAddress.getHostName();
                        } else {
                            tmpSelfIP = inetAddress.getCanonicalHostName();
                        }
                    } catch (UnknownHostException ignore) {
                        log.warn("Unable to retrieve localhost");
                    }
                }
                selfIP = tmpSelfIP;
            }
        };

        ipAutoRefresh.run();
    }

    public static String getSelfIP() {
        return selfIP;
    }

    public static void setSelfIP(String selfIP) {
        InetUtils.selfIP = selfIP;
    }
}
